<template>
	<view class="container" :class="themeClass">
		<!-- 顶部导航栏 -->
		<view class="header">
			<view class="nav-bar">
				<view class="nav-back" @tap="goBack">
					<uni-icons type="left" size="20" color="#333"></uni-icons>
					<text class="back-text">返回</text>
				</view>
				<text class="nav-title">开启两步验证</text>
				<view class="nav-right"></view>
			</view>
		</view>

		<!-- 页面内容 -->
		<view class="content">
			<!-- 步骤指示器 -->
			<view class="steps-indicator">
				<view class="step-item" :class="{ active: currentStep >= 1 }">
					<view class="step-number">1</view>
					<text class="step-text">安装应用</text>
				</view>
				<view class="step-line" :class="{ active: currentStep >= 2 }"></view>
				<view class="step-item" :class="{ active: currentStep >= 2 }">
					<view class="step-number">2</view>
					<text class="step-text">扫描二维码</text>
				</view>
				<view class="step-line" :class="{ active: currentStep >= 3 }"></view>
				<view class="step-item" :class="{ active: currentStep >= 3 }">
					<view class="step-number">3</view>
					<text class="step-text">验证绑定</text>
				</view>
			</view>

			<!-- 步骤1：安装应用 -->
			<view v-if="currentStep === 1" class="step-content">
				<view class="step-header">
					<view class="step-icon">
						<uni-icons type="download" size="32" color="#1890ff"></uni-icons>
					</view>
					<text class="step-title">第一步：安装身份验证器应用</text>
					<text class="step-desc">请先在您的手机上安装以下任一身份验证器应用</text>
				</view>

				<view class="app-list">
					<view class="app-item" v-for="app in authApps" :key="app.name">
						<view class="app-icon">
							<uni-icons :type="app.icon" size="24" :color="app.color"></uni-icons>
						</view>
						<view class="app-info">
							<text class="app-name">{{ app.name }}</text>
							<text class="app-desc">{{ app.desc }}</text>
						</view>
						<view class="app-action">
							<uni-button size="mini" type="primary" @tap="downloadApp(app.url)">下载</uni-button>
						</view>
					</view>
				</view>

				<uni-button class="next-btn" type="primary" @tap="nextStep">下一步</uni-button>
			</view>

			<!-- 步骤2：扫描二维码 -->
			<view v-if="currentStep === 2" class="step-content">
				<view class="step-header">
					<view class="step-icon">
						<uni-icons type="scan" size="32" color="#52c41a"></uni-icons>
					</view>
					<text class="step-title">第二步：扫描二维码</text>
					<text class="step-desc">使用身份验证器应用扫描下方二维码</text>
				</view>

				<view class="qr-section">
					<view class="qr-code" v-if="qrCodeData">
						<!-- 这里应该显示二维码，实际项目中需要使用二维码生成组件 -->
						<view class="qr-placeholder">
							<uni-icons type="scan" size="60" color="#ccc"></uni-icons>
							<text class="qr-text">二维码</text>
							<text class="qr-desc">{{ qrCodeData }}</text>
						</view>
					</view>
					<view v-else class="qr-loading">
						<uni-icons type="spinner-cycle" size="40" color="#1890ff"></uni-icons>
						<text class="loading-text">正在生成二维码...</text>
					</view>

					<view class="manual-setup">
						<text class="manual-title">手动设置</text>
						<text class="manual-desc">如果无法扫描二维码，请手动输入以下密钥：</text>
						<view class="secret-key" @tap="copySecret">
							<text class="secret-text">{{ secretKey || '获取中...' }}</text>
							<uni-icons type="copy" size="16" color="#1890ff"></uni-icons>
						</view>
					</view>
				</view>

				<view class="action-buttons">
					<uni-button class="back-btn" @tap="prevStep">上一步</uni-button>
					<uni-button class="next-btn" type="primary" @tap="nextStep">下一步</uni-button>
				</view>
			</view>

			<!-- 步骤3：验证绑定 -->
			<view v-if="currentStep === 3" class="step-content">
				<view class="step-header">
					<view class="step-icon">
						<uni-icons type="checkmarkempty" size="32" color="#52c41a"></uni-icons>
					</view>
					<text class="step-title">第三步：验证绑定</text>
					<text class="step-desc">请输入身份验证器应用中显示的6位验证码</text>
				</view>

				<view class="verify-section">
					<view class="code-input-group">
						<input 
							v-for="(digit, index) in codeDigits" 
							:key="index"
							class="code-digit" 
							type="number" 
							maxlength="1"
							v-model="codeDigits[index]"
							@input="onCodeInput(index, $event)"
							@focus="onCodeFocus(index)"
							:ref="'codeInput' + index"
						/>
					</view>

					<view class="verify-tips">
						<uni-icons type="info" size="16" color="#fa8c16"></uni-icons>
						<text class="tips-text">验证码每30秒更新一次，请及时输入</text>
					</view>

					<!-- 开发阶段：手动获取验证码按钮 -->
					<view class="dev-tools">
						<uni-button 
							class="get-code-btn" 
							size="mini" 
							type="default"
							@tap="autoFillCode"
						>
							获取验证码
						</uni-button>
					</view>
				</view>

				<view class="action-buttons">
					<uni-button class="back-btn" @tap="prevStep">上一步</uni-button>
					<uni-button 
						class="enable-btn" 
						type="primary" 
						:disabled="!canEnable"
						:loading="isEnabling"
						@tap="enable2FA"
					>
						{{ isEnabling ? '开启中...' : '开启两步验证' }}
					</uni-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';
	import themeManager from '@/utils/theme.js';

	// 响应式数据
	const currentStep = ref(1);
	const qrCodeData = ref('');
	const secretKey = ref('');
	const codeDigits = ref(['', '', '', '', '', '']);
	const isEnabling = ref(false);
	const themeClass = ref(themeManager.getThemeClass());

	// 身份验证器应用列表
	const authApps = ref([
		{
			name: 'Google Authenticator',
			desc: '谷歌官方身份验证器',
			icon: 'gear',
			color: '#4285f4',
			url: 'https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2'
		},
		{
			name: 'Microsoft Authenticator',
			desc: '微软身份验证器',
			icon: 'gear',
			color: '#00bcf2',
			url: 'https://www.microsoft.com/zh-cn/security/mobile-authenticator-app'
		},
		{
			name: 'Authy',
			desc: '功能丰富的验证器',
			icon: 'gear',
			color: '#ec1c24',
			url: 'https://authy.com/download/'
		}
	]);

	// 计算属性
	const canEnable = computed(() => {
		return codeDigits.value.every(digit => digit !== '');
	});

	const verificationCode = computed(() => {
		return codeDigits.value.join('');
	});

	// 主题变化监听
	const handleThemeChange = (isNightMode: boolean) => {
		themeClass.value = themeManager.getThemeClass();
	};

	// ==================== 后端接口定义 ====================
	// 前端人员：获取两步验证设置信息
	// BACKEND REQUIRED - 后端开发人员请实现以下接口
	// 
	// GET /api/account/security/2fa/setup
	// 请求头: Authorization: Bearer {token}
	// 响应 200:
	// {
	//   "success": true,
	//   "data": {
	//     "qrCodeUrl": "otpauth://totp/EduLiveLink:user@example.com?secret=JBSWY3DPEHPK3PXP&issuer=EduLiveLink",
	//     "secretKey": "JBSWY3DPEHPK3PXP",    // Base32编码的密钥
	//     "backupCodes": ["12345678", "87654321"]  // 备用恢复代码
	//   }
	// }
	// 响应 500: { "success": false, "message": "服务器错误" }
	// 生成6位随机验证码
	const generateRandomCode = () => {
		return Math.floor(100000 + Math.random() * 900000).toString();
	};

	// 自动填入验证码（开发阶段）
	const autoFillCode = () => {
		const verifyCode = generateRandomCode();
		
		// 显示验证码提示
		uni.showToast({
			title: `验证码: ${verifyCode}`,
			icon: 'none',
			duration: 5000
		});
		
		// 自动填入验证码
		setTimeout(() => {
			codeDigits.value = verifyCode.split('');
			console.log(`两步验证码: ${verifyCode}`);
		}, 1000);
	};

	const fetch2FASetup = () => {
		// 显示加载提示
		uni.showLoading({
			title: '获取中...'
		});

		// 模拟网络延迟
		setTimeout(() => {
			uni.hideLoading();
			
			// 生成模拟的二维码数据（开发阶段）
			const mockSecretKey = 'JBSWY3DPEHPK3PXP';
			const mockQrCodeUrl = `otpauth://totp/EduLiveLink:user@example.com?secret=${mockSecretKey}&issuer=EduLiveLink`;
			
			qrCodeData.value = mockQrCodeUrl;
			secretKey.value = mockSecretKey;
			
			console.log('两步验证设置信息已获取');
		}, 1000);
	};

	// 前端人员：开启两步验证
	// BACKEND REQUIRED - 后端开发人员请实现以下接口
	// 
	// POST /api/account/security/2fa/enable
	// 请求头: Authorization: Bearer {token}
	// 请求体: {
	//   "code": "123456"           // 6位验证码
	// }
	// 响应 200: 
	// {
	//   "success": true, 
	//   "message": "两步验证已开启",
	//   "data": {
	//     "backupCodes": ["12345678", "87654321"]  // 备用恢复代码
	//   }
	// }
	// 响应 400: { "success": false, "message": "验证码错误" }
	// 响应 409: { "success": false, "message": "两步验证已开启" }
	// 响应 500: { "success": false, "message": "开启失败" }
	const enable2FA = () => {
		if (!canEnable.value || isEnabling.value) return;

		isEnabling.value = true;

		// 显示加载提示
		uni.showLoading({
			title: '开启中...'
		});

		// 模拟网络延迟
		setTimeout(() => {
			uni.hideLoading();
			
			// 直接处理开启两步验证（开发阶段）
			uni.showToast({ title: '两步验证已开启', icon: 'success' });
			
			// 通知父页面更新安全信息
			uni.$emit('securityInfoUpdated', {
				type: 'twoFactor',
				value: true
			});
			
			// 生成模拟的备用恢复代码
			const mockBackupCodes = [
				Math.random().toString(36).substring(2, 10).toUpperCase(),
				Math.random().toString(36).substring(2, 10).toUpperCase()
			];
			
			// 显示备用恢复代码
			setTimeout(() => {
				uni.showModal({
					title: '备用恢复代码',
					content: `请保存以下备用代码，在无法使用验证器时可用于恢复：\n${mockBackupCodes.join('\n')}`,
					showCancel: false,
					confirmText: '已保存',
					success: () => {
						uni.navigateBack();
					}
				});
			}, 1500);
			
			isEnabling.value = false;
		}, 1000);
	};

	// 步骤导航
	const nextStep = () => {
		if (currentStep.value < 3) {
			currentStep.value++;
			if (currentStep.value === 2) {
				fetch2FASetup();
			} else if (currentStep.value === 3) {
				// 第三步时自动生成验证码
				autoFillCode();
			}
		}
	};

	const prevStep = () => {
		if (currentStep.value > 1) {
			currentStep.value--;
		}
	};

	// 下载应用
	const downloadApp = (url: string) => {
		uni.showModal({
			title: '下载提示',
			content: '将跳转到应用下载页面',
			success: (res) => {
				if (res.confirm) {
					// 在小程序中无法直接打开外部链接，这里仅作示意
					uni.showToast({ title: '请在浏览器中搜索下载', icon: 'none' });
				}
			}
		});
	};

	// 复制密钥
	const copySecret = () => {
		if (!secretKey.value) return;
		
		uni.setClipboardData({
			data: secretKey.value,
			success: () => {
				uni.showToast({ title: '密钥已复制', icon: 'success' });
			}
		});
	};

	// 验证码输入处理
	const onCodeInput = (index: number, event: any) => {
		const value = event.detail.value;
		if (value && /^\d$/.test(value)) {
			codeDigits.value[index] = value;
			// 自动跳转到下一个输入框
			if (index < 5) {
				nextTick(() => {
					// 注意：uni-app中ref的使用方式可能不同，这里仅作示意
					const nextInput = document.querySelector(`.code-digit:nth-child(${index + 2})`);
					if (nextInput) {
						(nextInput as HTMLInputElement).focus();
					}
				});
			}
		} else {
			codeDigits.value[index] = '';
		}
	};

	const onCodeFocus = (index: number) => {
		// 清空当前输入框
		codeDigits.value[index] = '';
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 生命周期
	onMounted(() => {
		themeManager.addListener(handleThemeChange);
	});

	onUnmounted(() => {
		themeManager.removeListener(handleThemeChange);
	});
</script>

<style>
	page {
		background-color: #f5f6fa;
	}

	.container {
		min-height: 100vh;
		background-color: #f5f6fa;
	}

	/* 顶部导航栏 */
	.header {
		background: #ffffff;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 0;
		z-index: 100;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 30rpx;
		height: 88rpx;
	}

	.nav-title {
		font-size: 18px;
		font-weight: 600;
		color: #333;
	}

	.nav-back {
		display: flex;
		align-items: center;
		gap: 8rpx;
		padding: 10rpx 16rpx;
		border-radius: 8rpx;
		transition: background-color 0.2s ease;
		cursor: pointer;
	}

	.nav-back:active {
		background-color: rgba(0, 0, 0, 0.05);
	}

	.back-text {
		font-size: 16px;
		color: #333;
		font-weight: 500;
	}

	.nav-right {
		width: 40rpx;
	}

	/* 页面内容 */
	.content {
		padding: 40rpx 30rpx;
	}

	/* 步骤指示器 */
	.steps-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 60rpx;
		padding: 0 40rpx;
	}

	.step-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 12rpx;
		opacity: 0.4;
		transition: opacity 0.3s ease;
	}

	.step-item.active {
		opacity: 1;
	}

	.step-number {
		width: 60rpx;
		height: 60rpx;
		background: #d9d9d9;
		color: #999;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		font-weight: 600;
		transition: all 0.3s ease;
	}

	.step-item.active .step-number {
		background: #1890ff;
		color: #ffffff;
	}

	.step-text {
		font-size: 12px;
		color: #999;
		transition: color 0.3s ease;
	}

	.step-item.active .step-text {
		color: #333;
	}

	.step-line {
		flex: 1;
		height: 2rpx;
		background: #d9d9d9;
		margin: 0 20rpx;
		transition: background-color 0.3s ease;
	}

	.step-line.active {
		background: #1890ff;
	}

	/* 步骤内容 */
	.step-content {
		background: #ffffff;
		border-radius: 20rpx;
		padding: 40rpx;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
	}

	.step-header {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.step-icon {
		width: 100rpx;
		height: 100rpx;
		background: linear-gradient(135deg, #1890ff, #40a9ff);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 auto 24rpx;
		box-shadow: 0 8rpx 32rpx rgba(24, 144, 255, 0.3);
	}

	.step-title {
		display: block;
		font-size: 20px;
		font-weight: 700;
		color: #333;
		margin-bottom: 16rpx;
	}

	.step-desc {
		display: block;
		font-size: 14px;
		color: #666;
		line-height: 1.6;
	}

	/* 应用列表 */
	.app-list {
		margin-bottom: 40rpx;
	}

	.app-item {
		display: flex;
		align-items: center;
		gap: 20rpx;
		padding: 24rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		margin-bottom: 16rpx;
		transition: background-color 0.3s ease;
	}

	.app-item:last-child {
		margin-bottom: 0;
	}

	.app-item:active {
		background: #f0f0f0;
	}

	.app-icon {
		width: 60rpx;
		height: 60rpx;
		background: #ffffff;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}

	.app-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 6rpx;
	}

	.app-name {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}

	.app-desc {
		font-size: 12px;
		color: #999;
	}

	.app-action {
		flex-shrink: 0;
	}

	/* 二维码区域 */
	.qr-section {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.qr-code {
		width: 400rpx;
		height: 400rpx;
		background: #ffffff;
		border: 2rpx solid #e9ecef;
		border-radius: 16rpx;
		margin: 0 auto 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.qr-placeholder {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16rpx;
		color: #ccc;
	}

	.qr-text {
		font-size: 16px;
		font-weight: 600;
	}

	.qr-desc {
		font-size: 12px;
		color: #999;
		word-break: break-all;
		max-width: 300rpx;
		text-align: center;
	}

	.qr-loading {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 16rpx;
		color: #1890ff;
	}

	.loading-text {
		font-size: 14px;
	}

	.manual-setup {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
		text-align: left;
	}

	.manual-title {
		display: block;
		font-size: 16px;
		font-weight: 600;
		color: #333;
		margin-bottom: 12rpx;
	}

	.manual-desc {
		display: block;
		font-size: 14px;
		color: #666;
		margin-bottom: 16rpx;
		line-height: 1.6;
	}

	.secret-key {
		display: flex;
		align-items: center;
		justify-content: space-between;
		background: #ffffff;
		border: 2rpx solid #e9ecef;
		border-radius: 8rpx;
		padding: 16rpx;
		cursor: pointer;
		transition: all 0.3s ease;
	}

	.secret-key:active {
		background: #f0f0f0;
		border-color: #1890ff;
	}

	.secret-text {
		font-size: 14px;
		font-family: monospace;
		color: #333;
		word-break: break-all;
		flex: 1;
		margin-right: 16rpx;
	}

	/* 验证区域 */
	.verify-section {
		text-align: center;
		margin-bottom: 40rpx;
	}

	.code-input-group {
		display: flex;
		justify-content: center;
		gap: 16rpx;
		margin-bottom: 30rpx;
	}

	.code-digit {
		width: 80rpx;
		height: 80rpx;
		background: #f8f9fa;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		text-align: center;
		font-size: 24px;
		font-weight: 600;
		color: #333;
		transition: all 0.3s ease;
	}

	.code-digit:focus {
		border-color: #1890ff;
		background: #ffffff;
		box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
	}

	.verify-tips {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8rpx;
		color: #fa8c16;
	}

	.tips-text {
		font-size: 14px;
	}

	/* 按钮组 */
	.action-buttons {
		display: flex;
		gap: 20rpx;
	}

	.back-btn {
		flex: 1;
		height: 88rpx;
		background: #f8f9fa;
		color: #666;
		border: 2rpx solid #e9ecef;
		border-radius: 12rpx;
		font-size: 16px;
		font-weight: 600;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.next-btn {
		flex: 1;
		height: 88rpx;
		background: linear-gradient(135deg, #1890ff, #40a9ff);
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 16px;
		font-weight: 600;
		border: none;
		box-shadow: 0 4rpx 16rpx rgba(24, 144, 255, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.enable-btn {
		flex: 1;
		height: 88rpx;
		background: linear-gradient(135deg, #52c41a, #73d13d);
		color: #ffffff;
		border-radius: 12rpx;
		font-size: 16px;
		font-weight: 600;
		border: none;
		box-shadow: 0 4rpx 16rpx rgba(82, 196, 26, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	.enable-btn:disabled {
		background: #d9d9d9;
		color: #999;
		box-shadow: none;
	}

	/* 开发工具样式 */
	.dev-tools {
		margin-top: 32rpx;
		display: flex;
		justify-content: center;
	}

	.get-code-btn {
		height: 64rpx;
		padding: 0 32rpx;
		background: linear-gradient(135deg, #fa8c16, #ffa940);
		color: #ffffff;
		border-radius: 8rpx;
		font-size: 14px;
		font-weight: 500;
		border: none;
		box-shadow: 0 2rpx 8rpx rgba(250, 140, 22, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		line-height: 1;
	}

	/* 夜间模式适配 */
	.night-mode {
		background-color: #1a1a1a;
	}

	.night-mode .header {
		background: #2c2c2c;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.3);
	}

	.night-mode .nav-title {
		color: #e0e0e0;
	}

	.night-mode .nav-back:active {
		background-color: rgba(255, 255, 255, 0.1);
	}

	.night-mode .back-text {
		color: #e0e0e0;
	}

	.night-mode .step-content {
		background: #2c2c2c;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.2);
	}

	.night-mode .step-title {
		color: #e0e0e0;
	}

	.night-mode .step-desc {
		color: #b0b0b0;
	}

	.night-mode .app-item {
		background: #3a3a3a;
	}

	.night-mode .app-name {
		color: #e0e0e0;
	}

	.night-mode .app-desc {
		color: #b0b0b0;
	}

	.night-mode .qr-code {
		background: #3a3a3a;
		border-color: #4a4a4a;
	}

	.night-mode .manual-setup {
		background: #3a3a3a;
	}

	.night-mode .manual-title {
		color: #e0e0e0;
	}

	.night-mode .manual-desc {
		color: #b0b0b0;
	}

	.night-mode .secret-key {
		background: #2c2c2c;
		border-color: #4a4a4a;
	}

	.night-mode .secret-text {
		color: #e0e0e0;
	}

	.night-mode .code-digit {
		background: #3a3a3a;
		border-color: #4a4a4a;
		color: #e0e0e0;
	}

	.night-mode .code-digit:focus {
		background: #3a3a3a;
	}

	.night-mode .back-btn {
		background: #3a3a3a;
		color: #e0e0e0;
		border-color: #4a4a4a;
	}
</style>


